<template>
  <div class="camera-container">
    <!-- 打开摄像头按钮 -->
    <button 
      v-if="!isCameraOpen && !photo" 
      @click="openCamera" 
      class="btn"
    >
      打开摄像头
    </button>

    <!-- 实时视频显示 -->
    <video 
      ref="videoElement" 
      v-show="isCameraOpen" 
      autoplay 
      class="video-preview"
    ></video>

    <!-- 拍照按钮 -->
    <button 
      v-if="isCameraOpen" 
      @click="capturePhoto" 
      class="btn capture-btn"
    >
      拍摄
    </button>

    <!-- 照片预览和操作 -->
    <div v-if="photo" class="preview-container">
      <img :src="photo" alt="拍摄的图片" class="photo-preview">
      <div class="action-btns">
        <button @click="retakePhoto" class="btn retake-btn">重拍</button>
        <button @click="downloadPhoto" class="btn download-btn">开始验证</button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
export default {
  data() {
    return {
      isCameraOpen: false,  // 摄像头开启状态
      photo: null,         // 照片数据URL
      mediaStream: null,    // 媒体流对象
      base64Data: null, // 新增base64存储字段 
      uploadUrl: 'http://localhost:8088/image' // 验证接口 
    };
  },
  methods: {
    // 打开摄像头
    async openCamera() {
      try {
        // 请求摄像头权限
        const stream = await navigator.mediaDevices.getUserMedia({
          video: { facingMode: "user" } // 前置摄像头（environment 后置）
        });
        
        // 释放之前的流（如果存在）
        if (this.mediaStream) {
          this.mediaStream.getTracks().forEach(track => track.stop());
        }
        
        // 初始化视频元素
        this.mediaStream = stream;
        const video = this.$refs.videoElement;
        video.srcObject = stream;
        await video.play();
        this.isCameraOpen = true;
        
      } catch (error) {
        console.error("摄像头访问失败:", error);
        alert("无法访问摄像头，请检查权限和连接！");
      }
    },

    async uploadphoto(){
    const formData = new FormData();
    formData.append( 'photo',this.photo);
    const res = await fetch('http://localhost:8088/face', {
    method:'POST',
    body:formData
    })
    const data = await res.json();},
    // 拍摄照片
    async  capturePhoto() {
     
      const video = this.$refs.videoElement; 
      const canvas = document.createElement('canvas'); 
     
      // 设置画布尺寸与视频一致
      canvas.width  = video.videoWidth; 
      canvas.height  = video.videoHeight; 
       // 生成Base64 
      this.photo  = canvas.toDataURL('image/jpeg',  0.8); // 压缩质量0.8 
      this.base64Data  = this.photo.split(',')[1];  // 去除前缀[1]()
      
      // 绘制当前帧到画布
      canvas.getContext('2d').drawImage(video,  0, 0);
      
      // 生成图片并关闭摄像头
      this.photo = canvas.toDataURL('image/jpeg');
      this.isCameraOpen = false;
      this.mediaStream.getTracks().forEach(track => track.stop());
      this.photo = canvas.toDataURL('image/jpeg');
      
    //发送后端
      try {
          const response = await axios.post(this.uploadUrl,  {
            image: this.base64Data  
          }, {
            headers: {
              'Content-Type': 'application/json'
            }
          }
        );
    }catch (error) {
          console.error(' 验证失败:', error);
          this.verificationStatus  = '验证异常';
        }
  },
    

    // 重拍照片
    retakePhoto() {
      this.photo = null;
      this.openCamera();
    },

    // 验证照片
    downloadPhoto() {
      const link = document.createElement('a');
      link.download = 'photo.png';
      link.href = this.photo;
      link.click();
    }
  },
  
  // 组件销毁前清理资源
  beforeDestroy() {
    if (this.mediaStream) {
      this.mediaStream.getTracks().forEach(track => track.stop());
    }
  }
};
</script>

<style>
.camera-container {
  text-align: center;
  margin: 20px;
}

.video-preview {
  width: 100%;
  max-width: 600px;
  border: 2px solid #ddd;
  border-radius: 8px;
  margin: 10px 0;
}

.photo-preview {
  width: 100%;
  max-width: 500px;
  border: 2px solid #ddd;
  border-radius: 8px;
  margin: 10px 0;
}

.btn {
  padding: 10px 20px;
  margin: 5px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  background-color: #4CAF50;
  color: white;
  transition: background 0.3s;
}

.btn:hover {
  background-color: #45a049;
}

.capture-btn {
  background-color: #f44336;
}

.capture-btn:hover {
  background-color: #da190b;
}

.retake-btn {
  background-color: #2196F3;
}

.download-btn {
  background-color: #9C27B0;
}

.action-btns {
  margin-top: 10px;
}
</style>